package com.nextive.weightlogger.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Date utilities.
 * 
 * @author Federico Baseggio <fedebaseggio@gmail.com>
 */
public class DateUtil {
	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
			"EEE MMM/dd/yyyy");
	private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat(
			"h:mm a z");
	
	/**
	 * Returns a human-friendly string representation of the date specified.
	 * 
	 * @param calendar The date to format.
	 * @return A human-friendly string representation of the date specified.
	 */
	public static String getFormattedDate(Calendar calendar)
	{
		return DATE_FORMAT.format(calendar.getTime());
	}

	/**
	 * Returns a human-friendly string representation of the time specified.
	 * 
	 * @param calendar The time to format.
	 * @return A human-friendly string representation of the time specified.
	 */
	public static String getFormattedTime(Calendar calendar)
	{
		return TIME_FORMAT.format(calendar.getTime());
	}
	
	/**
	 * Returns an instance of {@link Calendar} set to the date and time
	 * specified.
	 * 
	 * @param unixTime
	 *            The unix time value to represent.
	 * @return An instance of {@link Calendar} set to the date and time
	 *         specified.
	 */
	public static Calendar fromUnixTime(long unixTime)
	{
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(unixTime * 1000);
		return calendar;
	}
	
	/**
	 * Returns the unix time value equivalent to the date and time specified.
	 * 
	 * @param calendar
	 *            The date and time to represent.
	 * @return The unix time value equivalent to the date and time specified.
	 */
	public static long toUnixTime(Calendar calendar)
	{
		return (long) Math.floor(calendar.getTimeInMillis() / 1000);
	}
}
